const { ErrorModel } = require('../model/resModel')
const {TokenConf} =  require('../conf/config')
const jwt = require('jsonwebtoken')
module.exports =  async (ctx,next)=>{
    const token = ctx.header['authorization']
    const url = ctx.request.url;
    // 不需要token的域名
    if(!token){
        ctx.body=new ErrorModel('未获取到token')
        return
    }
    const payload = await jwt.verify(token,TokenConf.secret).catch(err=>{
        console.log(err);
        throw(err)
    })
    // console.log(payload)
    const {id,exp,iat}=payload
    const mydate=new Date().getTime()
    if(mydate-exp>0){
        ctx.userId=id
        // app.context.userId = id;
        // ctx.set('userId', id);
        ctx.state['user']=id;
        await next();
        return
    }
    ctx.body=new ErrorModel('token已过期')
}